package cn.miju.common.util;

/**
 * <pre>
 * Cron表达式生成工具类
 * </pre>
 *
 * @author zhuming
 * @version 1.0.0
 * @since 2023-03-11 16:24
 */
public class CronUtil {
    /**
     * 构建Cron表达式
     *@param  delayTime 延迟时间;单位：秒
     *@return String
     */
    public static String createCronExpression(int delayTime){
        StringBuilder cronExp = new StringBuilder();
        TimeType timeType = TimeType.SECOND;
        int time = 0;
        if (delayTime < 60) {
            time = delayTime;
        } else if (delayTime < 3600 && delayTime % 60 == 0) {
            time = delayTime / 60;
            timeType = TimeType.MINUTE;
        } else if (delayTime < (24 * 3600) && delayTime % 3600 == 0) {
            time = delayTime / 3600;
            timeType = TimeType.HOUR;
        } else {
            throw new RuntimeException("暂不支持该时间值对应Cron表达式生成");
        }
        if (TimeType.SECOND.equals(timeType)) {
            cronExp.append("0/").append(time).append(" ");
            cronExp.append("* ");
            cronExp.append("* ");
        } else if (TimeType.MINUTE.equals(timeType)) {
            cronExp.append("0 ");
            cronExp.append("0/").append(time).append(" ");
            cronExp.append("* ");
        } else {
            cronExp.append("0 ");
            cronExp.append("0 ");
            cronExp.append("0/").append(time).append(" ");
        }
        cronExp.append("* ");
        cronExp.append("* ");
        cronExp.append("?");
        return cronExp.toString();
    }

    public enum TimeType {
        //秒
        SECOND(59),
        //分钟
        MINUTE(59),
        //小时
        HOUR(23)
        ;
        /**
         * 最大值
         */
        private Integer maxValue;

        public Integer getMaxValue() {
            return maxValue;
        }

        public void setMaxValue(Integer maxValue) {
            this.maxValue = maxValue;
        }

        TimeType(Integer maxValue) {
            this.maxValue = maxValue;
        }
    }



    //参考例子
    public static void main(String[] args) {
        System.out.println(CronUtil.createCronExpression(60));
    }

}
